<script>
	import * as DB from "@/compoment/DB.js"
	import {findDBShelfBook,findBookChapter,removeBookChapters} from "@/compoment/index.js"
	import {getBookChapters} from "@/compoment/httpBook.js"
	import tableJson from "@/compoment/table.json"
	export default {
		globalData:{
			version:0
		},
		onLaunch: function() {
			this.checkVersion()
			this.createAllTable()
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
			let hour = new Date().getHours()
			this.update()
		},
		methods:{ 
			 checkVersion(){
				uni.getSystemInfo({
					success: (res) => { 
						getApp().globalData.version = res.appWgtVersion.split(".").join("")
					}
				})
				 
			},
			async update(){
				let dbBooks = await findDBShelfBook()
				for(let i =0;i<dbBooks.length;i++){
					let httpBookChapters = await getBookChapters(dbBooks[i].fictionId)
					let dbBookChapters = await findBookChapter(dbBooks[i])
					const httpBookChaptersSize = httpBookChapters.length
					const dbBookChaptersSize = dbBookChapters.length
					if(httpBookChaptersSize == dbBookChaptersSize){
						return false
					}else{ //网络数量和本地数量不一致，更新
						uni.createPushMessage({
							content:"后台正在更新收藏书籍的章节"
						})
						// 删除本地
						try{
							removeBookChapters(dbBooks[i])
							//更新本地
							let fictionId = dbBooks[i].fictionId
							httpBookChapters.forEach((chapter)=>{
								let obj = {
									'fictionId':fictionId,
									'title':chapter.title,
									'chapterId':chapter.chapterId
								}
								DB.insert(DB.config.tables.uu_bookChapter,obj)
							})
							uni.createPushMessage({
								content:"更新完毕"
							})
						}catch(e){
							//TODO handle the exception
							uni.createPushMessage({
								content:"更新失败"
							})
						}
					}
				}
				
			},
			createAllTable(){
				let open = DB.isOpen()
				if(!open){//没有打开就打开
					DB.openSqlite().then((res)=>{console.log("数据库打开成功")})
					this.createAllTable()
				}else{//一打开，创建所有的表
					let tables = tableJson
					tables.forEach(obj=>{
							DB.createTable(obj.tableName,obj.columns)
								.then(()=>{
									console.log("创建"+obj.tableName+"成功")
								}).catch(()=>{
									console.log("创建"+obj.tableName+"失败")
								})
					})
				}
			}
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import url("@/static/iconfont/iconfont.css");
	image{will-change: transform}
	page{
		height: 100%;
	}	
</style>
